'''
Created on Jan 25, 2011

@author: Jialai_Zhu
'''
import process
import os
class wget(process.ChildProcess):
    '''
    classdoc
        '''
    name=''
    class wget_result():
        def __init__(self):
            self.host_ip=''
            self.download_folder=''
            self.download_time=''
            self.http_code=-1
            self.download_file=''
    def __init__(self,url,path,l=1,Q=None,r=''):
        import os
        import random
        import string
        self.log_file=string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 7)).replace(" ","")
        exe=os.path.join(os.path.dirname(__file__),'wget.exe')
        para={}
        para['-o']=self.log_file
        para['-t1']=''
        para['-x']=''
        para['-T10']=''
        para['-np']=''
        para['-P']=path
        para['-l']=l
        para['-Q']=Q
        para['-R']='mp3,wma,avi'
        para['-r']=r
        
        
        arg='"'+exe+'"'
        for p in para:
            if para[p]==None:
                pass
            arg=arg+' '+p+' '+str(para[p])
        arg=arg+' '+url
        print arg
        
#        if Q==None:
#            arg='%s -np  -o %s -t1 -T10 -x -P %s -l %d -r %s  -R mp3,wma'%(exe,self.log_file,path,l,url)
#        else:
#            arg='%s -np -Q %s -o %s -t1 -T10 -x -P %s -l %d -r %s -R mp3,wma'%(exe,Q,self.log_file,path,l,url)
#        print arg
        self.url=url
        self.wget_result=wget.wget_result()
        process.ChildProcess.__init__(self,wget.name,arg,shell=False)
        
    def RunAndWait(self,time_out):
        if process.ChildProcess.RunAndWait(self,time_out):
            pass
    def Result(self):
        return self.wget_result
    def ResultFromLog(self):
        import re
        line=open(self.log_file,'rb').readlines()
        try:
            s=re.search("--(\d+):(\d+):(\d+)--",line[0]).groups()
            self.download_time=s[0]+':'+s[1]+':'+s[2]
        except Exception,ex:
            pass  
        
        def find_http_code(self,line):            
            try:
                s=re.search(" (\d\d\d) ",line).groups()
                self.wget_result.http_code=int(s[0])
                return True
            except Exception,ex:
                return False
                pass  
        if (find_http_code(self,line[4])==False):
            find_http_code(self,line[3])
        try:
            import os
            for s in line:
                if s.find('saved')>0:
                    s=s.split('\'')
                    s=s[0].split('`')[1]
                    self.wget_result.download_folder=os.path.dirname(s)
                    self.wget_result.download_file = s
                    break
            pass
        except Exception,ex:
            pass  
        try:
#            textreg=re.search(regx_lib().url2,self.data).groups() 
            reobj = re.compile('(\d+).(\d+).(\d+).(\d+)')
            result = reobj.search(line[2])   
            for match in reobj.finditer(line[2]):
                try:
                    s=match.start()
                    e=match.end()
                    g=match.group()
                    self.wget_result.host_ip=self.host_ip+'['+g+']'
                    pass
                except Exception,ex:
                    pass
        except Exception,ex:
            pass  
        
        try:os.remove(self.log_file)
        except:pass
        return self.wget_result
    def __del__(self):
        try:os.remove(self.log_file)
        except:pass
        pass
   
#        import subprocess
#        data=subprocess.Popen(app+'  '+arg,shell=True)
def Cleanup():
    process.Wait(wget.name)       